<template>
  <body>
    <ParentHeader></ParentHeader>
    <div v-if="columnDetail" class="news-container">
      <!-- 显示馆院简讯子专栏内容 -->
      <div v-if="specialColumns.length > 0" class="special-columns">
        <div v-for="(child, index) in specialColumns" :key="index"
          :class="['news-item', { 'left': index % 2 === 0, 'right': index % 2 !== 0 }]">

          <div class="header-container">
            <div class="news-title">{{ child.name }}</div>
            <div @click="gotoDetail(child.columnId)" class="news-footer">更多 ></div>
          </div>

          <!-- 根据子专栏类型显示不同内容 -->
          <template v-if="child.name === '活动视频'">
            <div class="activity-video-container" v-for="article in activityVideoArticles" :key="article.id"
              @click="viewArticle(article.articleId)">
              <video controls>
                <source :src="article.videoUrl" type="video/mp4">
                您的浏览器不支持 video 显示
              </video>
            </div>
          </template>
          <template v-else-if="child.name === '通知公告'">
            <div class="news-content" v-for="article in noticeAnnouncementArticles" :key="article.id"
              @click="viewArticle(article.articleId)">
              <h3>标题：{{ article.title }}</h3>
              <span>发布时间：{{ article.updatedTime }}</span>
            </div>
          </template>
        </div>
      </div>

      <!-- Tab 切换其他子专栏 -->
      <div v-if="otherColumns.length > 0" class="tabbed-columns">
        <div class="tabs">
          <div v-for="(child, index) in otherColumns" :key="index"
            :class="['tab-item', { 'active': activeTab === child.columnId }]" @click="changeTab(child)">
            {{ child.name }}
          </div>
          <div @click="gotoDetail(selectedColumn?.columnId)" class="news-footer1" style=" margin-top: 22px;">更多 ></div>
        </div>
        <div class="selected-column-content" v-if="selectedColumn">
          <div v-for="article in articleList" :key="article.id" @click="viewArticle(article.articleId)"
            class="article-container">
            <img :src="article.coverImageUrl" alt="" class="article-image">
            <div class="article-info">
              <h3>{{ article.title }}</h3>
              <p>简介：{{ article.resume }}</p>
              <span>来源：{{ article.source }} 时间：{{ article.updatedTime }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <Footer></Footer>
  </body>
</template>

<script>
import { defineComponent, onMounted, computed, watch, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useColumnsStore } from '@/store/column';
import Footer from '../components/footer.vue';
import ParentHeader from '../components/parentHeader.vue';
import { getColumnDetailService, getArticleListService } from '@/api/user.js';

export default defineComponent({
  name: "NewsColumnDetail",
  components: {
    Footer,
    ParentHeader,
  },
  setup() {
    const columnsStore = useColumnsStore();
    const route = useRoute();
    const router = useRouter();
    const columnDetail = ref(null);
    const selectedColumn = ref(null);
    const activeTab = ref(null);

    // 获取栏目详情数据
    const fetchColumnDetail = async (id) => {
      try {
        const response = await getColumnDetailService(id);
        columnDetail.value = response.data;
      } catch (error) {
        console.error("Failed to fetch column detail:", error);
      }
    };

    // 跳转到详情页面
    const gotoDetail = (columnId) => {
      router.push({ name: 'AllArticles', params: { id: columnId } });
    };


    const articleList = ref([]); // 存储文章列表
    const loadingArticles = ref(false); // 加载状态
    const pageNum = ref(1);
    const pageSize = ref(10);

    // 获取文章列表的方法
    const fetchArticleList = async (subColumnId) => {
      loadingArticles.value = true;
      try {
        const params = { pageNum: pageNum.value, pageSize: pageSize.value, subColumnId };
        const response = await getArticleListService(params);
        articleList.value = response.data.slice(0, 6); // 最多6条
      } catch (error) {
        console.error("Failed to fetch article list:", error);
      } finally {
        loadingArticles.value = false;
      }
    };

    const activityVideoArticles = ref([]);
    const noticeAnnouncementArticles = ref([]);

    const fetchSpecialColumnArticles = async (subColumnId, columnName) => {
      try {
        const params = { pageNum: pageNum.value, pageSize: pageSize.value, subColumnId };
        const response = await getArticleListService(params);
        if (columnName === '活动视频') {
          activityVideoArticles.value = response.data.slice(0, 4); // 最多4条
        } else if (columnName === '通知公告') {
          noticeAnnouncementArticles.value = response.data.slice(0, 5); // 最多5条
        }
      } catch (error) {
        console.error("Failed to fetch special column article list:", error);
      }
    };

    // 在 changeTab 方法中调用 fetchArticleList 来获取新选中子专栏的文章列表
    const changeTab = (child) => {
      selectedColumn.value = child;
      activeTab.value = child.columnId;
      fetchArticleList(child.columnId);
    };

    // 当页面首次加载或路由参数变化时获取文章列表
    watch(() => route.params.id, async (newId) => {
      if (newId) {
        await Promise.all([fetchColumnDetail(newId), columnsStore.fetchChildrenColumns(newId)]);

        // 加载特殊专栏的数据
        specialColumns.value.forEach(child => {
          if (['活动视频', '通知公告'].includes(child.name)) {
            fetchSpecialColumnArticles(child.columnId, child.name);
          }
        });

        // 默认选择第一个非特殊子栏目
        const nonSpecialColumns = otherColumns.value;
        if (nonSpecialColumns.length > 0) {
          changeTab(nonSpecialColumns[0]);
        }
      }
    }, { immediate: true });

    // 计算属性用于筛选出特殊的子栏目（活动视频、通知公告）
    const specialColumns = computed(() =>
      columnsStore.childrenColumns.filter(child => ['活动视频', '通知公告'].includes(child.name))
    );

    // 计算属性用于筛选出其他的子栏目
    const otherColumns = computed(() =>
      columnsStore.childrenColumns.filter(child => !['活动视频', '通知公告'].includes(child.name))
    );

    // 定义 viewArticle 方法
    const viewArticle = (articleId) => {
      router.push({ name: 'ArticleDetail', params: { id: articleId } });
    };

    return {
      columnDetail,
      childrenColumns: computed(() => columnsStore.childrenColumns),
      gotoDetail,
      specialColumns,
      otherColumns,
      selectedColumn,
      changeTab,
      activeTab,
      articleList,
      loadingArticles,
      fetchArticleList,
      activityVideoArticles,
      noticeAnnouncementArticles,
      fetchSpecialColumnArticles,
      viewArticle // 返回 viewArticle 方法
    };
  }
});
</script>

<style scoped>@import '../assets/css/columns/news-column-detail.css';</style>